using Identity.Application.Contracts.Common;
using Identity.Application.Contracts.Services;
using Identity.Application.UserRoles.Commands;
using Identity.Domain.Aggregates;
using MediatR;

namespace Identity.Application.UserRoles.CommandHandlers;

public class AddUserToRoleCommandHandler : IRequestHandler<AddUserToRoleCommand, Result>
{
    private readonly IUserService _userService;
    private readonly IRoleService _roleService;
    private readonly IUserRoleService _userRoleService;

    public AddUserToRoleCommandHandler(IUserRoleService userRoleService, IUserService userService, IRoleService roleService)
    {
        _userRoleService = userRoleService;
        _roleService = roleService;
        _userService = userService;
    }
    public async Task<Result> Handle(AddUserToRoleCommand request, CancellationToken cancellationToken)
    {
        var userData = await _userService.GetUserByIdAsync(request.UserId);
        
        var roles = new List<Role>();
        foreach (var roleId in request.RoleIds)
        {
            var roleData = await _roleService.GetRoleByIdAsync(roleId);
            roles.Add(Role.LoadFromPersistence(roleData!.Id,roleData.Code, roleData.Name,roleData.PermissionIds, roleData.Description,roleData.Status));
        }

        var user = UserAggregate.LoadFromPersistence(userData!.Id,userData.UserName,userData.Email,userData.Roles.ToList());

        foreach (var role in roles)
        {
            user.AddRoles(role.Name);
        }


        var result = await _userRoleService.AddRolesAsync(request.UserId, request.RoleIds);
        if (!result) return Result.Failure("添加角色失败");

        return Result.Success();
    }
}